﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace JH
{
    public static class GetClassInheritanceChain
    {
        /// <summary>
        /// 从当前类类型一直溯源到继承链指定类型
        /// </summary>
        /// <param name="type">当前类型</param>
        /// <param name="stopAt">基类型</param>
        /// <param name="isIncludeSelf">是否包含当前类型自身</param>
        /// <param name="fromRoot">true时，返回栈的栈顶元素为当前类型，false时，返回栈的栈顶元素为stopAt基类型</param>
        /// <returns>返回找到的继承链</returns>
        public static IEnumerable<Type> GetInheritanceChainEm(this Type type, Type stopAt, bool isIncludeSelf = false,
            bool fromRoot = true)
        {
            if (type == null) throw new ArgumentNullException(nameof(type), "传入了空的Type");
            if (stopAt == null) throw new ArgumentNullException(nameof(stopAt), "传入了空的Type");
            if (!type.IsClass || !stopAt.IsClass) throw new ArgumentException(" 传入参数类型不是类的类型！");
            if (!stopAt.IsAssignableFrom(type)) throw new ArgumentException("传入的类型不是当前类型的基类！");

            var chain = new Stack<Type>();
            if (isIncludeSelf) chain.Push(type);
            while (type != stopAt && type.BaseType != null)
            {
                type = type.BaseType;
                chain.Push(type);
            }

            // 反转列表，使其从指定的基类开始
            return fromRoot ? chain.Reverse() : chain;
        }
    }
}